package config

import (
	"flag"
	"gopkg.in/yaml.v2"
	"os"
)

var configFile = flag.String("config", "config/app.yaml", "application config path")

type Config struct {
	Server      ServerConfig `yaml:"server"`
	Redis       RedisConfig  `yaml:"redis"`
	RunMode     string
	WWW         string
	Swagger     bool
	PrintConfig bool
	Captcha     Captcha
	CORS        CORS
}

type ServerConfig struct {
	Port int `yaml:"port"`
}

type RedisConfig struct {
	Host string `yaml:"host"`
	Port int    `yaml:"port"`
}

type Captcha struct {
	Store       string
	Length      int
	Width       int
	Height      int
	RedisDB     int
	RedisPrefix string
}

type CORS struct {
	Enable           bool
	AllowOrigins     []string
	AllowMethods     []string
	AllowHeaders     []string
	AllowCredentials bool
	MaxAge           int
}

func Parse() (*Config, error) {
	config := &Config{}

	file, err := os.Open(*configFile)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	if err := yaml.NewDecoder(file).Decode(&config); err != nil {
		return nil, err
	}

	return config, nil
}

func (c *Config) IsDebugMode() bool {
	return c.RunMode == "debug"
}
